package com.blogs.security.login;

import com.blogs.common.constant.WebConst;
import com.blogs.common.utils.ApiResult;
import com.blogs.common.utils.ResponseUtils;
import com.blogs.domain.db.SysUser;
import com.blogs.security.dto.SecurityUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description
 *
 * @author hubiao
 * @since 2020-09-28 9:30
 */
@Component
public class AdminAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        SysUser user = new SysUser();
        SecurityUser securityUser = ((SecurityUser) auth.getPrincipal());
        user.setToken( securityUser.getCurrentUserInfo().getToken() );
        httpServletRequest.getSession().setAttribute( WebConst.LOGIN_SESSION_KEY, user );
        SavedRequest savedRequest = (SavedRequest) httpServletRequest.getSession().getAttribute( "SPRING_SECURITY_SAVED_REQUEST" );
        if (savedRequest != null) {
            httpServletRequest.getSession().removeAttribute( "SPRING_SECURITY_SAVED_REQUEST" );
        }
        ResponseUtils.out( response, ApiResult.ok( "登录成功!", user ) );
    }
}
